package org.wii.config.sentinel;

import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.wii.base.exception.IWiiException;

/**
 * @author tanghong on 2022/12/23
 */
@Slf4j
@Configuration
@AutoConfigureBefore(SentinelFeignAutoConfiguration.class)
public class SentinelConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public BlockExceptionHandler blockExceptionHandler() {
        return (httpServletRequest, httpServletResponse, e) -> {
            String requestURI = httpServletRequest.getRequestURI();
            log.error("SentinelException {} ==> {}", e.getRuleLimitApp(), requestURI);
            if (e instanceof FlowException) {
                throw new IWiiException(SentinelExceptionEnum.FLOW);
            } else if (e instanceof DegradeException) {
                throw new IWiiException(SentinelExceptionEnum.DEGRADE);
            } else if (e instanceof ParamFlowException) {
                throw new IWiiException(SentinelExceptionEnum.PARAM);
            } else if (e instanceof SystemBlockException) {
                throw new IWiiException(SentinelExceptionEnum.SYSTEM_BLOCK);
            } else if (e instanceof AuthorityException) {
                throw new IWiiException(SentinelExceptionEnum.AUTHORITY);
            }
        };
    }
}
